package cn.sc.summer.feign.client;

import cn.sc.summer.feign.vo.UserInfoFeignVO;
import cn.sc.summer.constant.model.Result;
import cn.sc.summer.feign.config.FeignRequestConfig;
import cn.sc.summer.token.po.AuthorityX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Set;

/**
 * 接口：SysFeignClient
 *
 * @author a-xin
 * @date 2023/9/3 11:57
 */
@FeignClient(name = "${feign.client.server}", fallbackFactory = SysFeignClient.SysFeignFallback.class, configuration = FeignRequestConfig.class)
public interface SysFeignClient {

    /**
     * 根据用户手机号查询用户信息
     *
     * @param phone 手机号
     * @return 用户信息
     */
    @RequestMapping(value = "/sys/userFeign/getUserInfoByPhone", method = RequestMethod.GET)
    Result<UserInfoFeignVO> getUserInfoByPhone(@RequestParam(value = "phone") String phone);

    /**
     * 缓存用户权限信息
     *
     * @param userId    用户ID
     * @param loginType 登录类型
     */
    @RequestMapping(value = "/sys/userFeign/getUserAuth", method = RequestMethod.GET)
    Result<Set<AuthorityX>> getUserAuth(@RequestParam(value = "userId") String userId, @RequestParam(value = "loginType") String loginType);

    @Slf4j
    @Component
    class SysFeignFallback implements FallbackFactory<SysFeignClient> {
        @Override
        public SysFeignClient create(Throwable cause) {
            log.error("Fallback reason:{}", cause.getMessage());
            return new SysFeignClient() {

                /**
                 * 根据用户手机号查询用户信息
                 *
                 * @param phone 手机号
                 * @return 用户信息
                 */
                @Override
                public Result<UserInfoFeignVO> getUserInfoByPhone(String phone) {
                    return Result.fallback(cause.getMessage());
                }

                /**
                 * 缓存用户权限信息
                 *
                 * @param userId 用户ID
                 * @param loginType 登录类型
                 */
                @Override
                public Result<Set<AuthorityX>> getUserAuth(String userId, String loginType) {
                    return Result.fallback(cause.getMessage());
                }

            };

        }
    }

}
